package com.mybatis.plug.config;

import com.mybatis.plug.util.PageUtil;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * type:需要代理的对象  method:代理方法  args:需要mybatis传递的值
 * mybatis拦截器
 * @author ytj
 * @date 2021/12/7
 */
@Intercepts(@Signature(type = StatementHandler.class,method = "prepare",args ={Connection.class,Integer.class} ))
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //获取目标对象
        StatementHandler statementHandler=(StatementHandler) invocation.getTarget();
        //获取元数据(mybatis提供)
        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
        //获取方法名称
        String value = (String) metaObject.getValue("delegate.mappedStatement.id");
        if(value.matches(".*ByPage$")){
            //获取连接对象
            Connection connection=(Connection)invocation.getArgs()[0];
            //获取方法中的sql
            String sql=statementHandler.getBoundSql().getSql();
            //编写查询总数sql
            String countSql="select count(1) from ("+sql+")  a";
            PreparedStatement preparedStatement = connection.prepareStatement(countSql);
            //添加查询条件
            ParameterHandler parameterHandler = statementHandler.getParameterHandler();
            parameterHandler.setParameters(preparedStatement);
            //执行总记录数sql
            ResultSet resultSet = preparedStatement.executeQuery();
            //获取传递参数
            PageUtil pageUtil=(PageUtil)parameterHandler.getParameterObject();
            if(resultSet.next()){
                int total=resultSet.getInt(1);
                pageUtil.setTotal(total);
            }
            //编写分页sql
            String pageSql=sql+" limit "+pageUtil.getPage()+","+pageUtil.getSize();
            //将分页sql放入到mybatis中
            metaObject.setValue("delegate.boundSql.sql", pageSql);
        }
        return invocation.proceed();
    }

    /**
     * 代理对象
     * */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    /**
     * 获取配置文件内容
     * */
    @Override
    public void setProperties(Properties properties) {

    }
}
